/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbSema.cpp			*/
/********************************************************/

#include "GlbSema.h"

namespace GlbCls
{

CGlbSema::CGlbSema()
{
	m_pstSema = NULL;
}

CGlbSema::~CGlbSema()
{
	m_pstSema = NULL;
}

int CGlbSema::GlbSemaPost()
{
	return sem_post(m_pstSema);
}

int CGlbSema::GlbSemaWait()
{
	return sem_wait(m_pstSema);
}

int CGlbSema::GlbSemaTryWait()
{
	return sem_trywait(m_pstSema);
}

void CGlbSema::GlbSemaDestroy()
{
	sem_destroy(m_pstSema);

	return;
}

int CGlbSema::GlbSemaGetValue(int& riValue)
{
	return sem_getvalue(m_pstSema, &riValue);
}

int CGlbSema::GlbSemaInit(int iShare, UINT uiVal)
{
	if (NULL != (m_pstSema = (sem_t*)malloc(sizeof(sem_t)))) {
		if (GLB_SUCCESS != sem_init(m_pstSema, iShare, uiVal)) {
			free(m_pstSema);
			goto GlbError;
		}
	}
	else {
		goto GlbError;
	}

	return GLB_SUCCESS;

GlbError:
	GLB_ERROR("%s\n", strerror(errno));

	return GLB_FAILURE;
}

void CGlbSema::GlbSemaClose()
{
	sem_close(m_pstSema);

	return;
}

void CGlbSema::GlbSemaUnlink(char* pszName)
{
	sem_unlink(pszName);

	return;
}

int CGlbSema::GlbSemaOpen(char* pszName, int iVal)
{
	if (NULL == (m_pstSema = sem_open(pszName, GLB_FLAGS, GLB_PERMS, iVal))) {
		if (NULL == (m_pstSema = sem_open(pszName, 0))) {
			GLB_ERROR("%s\n", strerror(errno));
			return GLB_FAILURE;
		}
	}

	return GLB_SUCCESS;
}

} /* GlbCls */
